package com.javaweb.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @desc: todo: 实现对 DAO层的所有方法的执行进行日志输出，日志信息
 *              包括如下：
 *              1） 方法名字
 *              2） 执行消耗时间（S）
 *
 * @author:
 * @date:
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    @Around("execution(* com.javaweb.dao..*.*(..))")
    public Object logAllDaoMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        Object result = null;

        try {
            result = joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("方法名：{}，执行发生异常：{}", methodName, throwable.getMessage());
            throw throwable; // 重新抛出异常
        } finally {
            long endTime = System.currentTimeMillis();
            double elapsedTimeInSeconds = (endTime - startTime) / 1000.0;
            log.info("方法名：{}，执行消耗时间：{}s，返回值：{}", methodName, elapsedTimeInSeconds, result);
        }

        return result;
    }
}
